#########################################
#			bootsect.s by doom119		#
#				April, 2010				#
#########################################
.code16
.text
.global _start
_start:
#move bootsect itself to 0x90000, and then jump there to continue
	mov %cs, %ax
	mov %ax, %ds
	mov $0x9000, %ax
	mov %ax, %es
	mov $0x7c00, %si
	xor %di, %di
	mov $256, %cx
	rep
	movsw

	ljmp $0x9000, $go

go:
	mov %cs, %ax
	mov %ax, %es
	mov %ax, %ds
	mov %ax, %ss
	mov $0xFF00, %sp

#showing "Loading system..." on screen
	mov $2, %ah
	xor %bx, %bx
	int $0x10

	mov $0x1301, %ax
	mov $output, %bp
	mov $17, %cx
	mov $0xc, %bx
	int $0x10
	
#read 4 setup sectors to 0x90200
1:
	mov $0x0204, %ax
	mov $2, %cx
	xor %dx, %dx
	mov $0x0200, %bx
	int $0x13
	jnc 2f
	xor %ax, %ax
	xor %dx, %dx
	int $0x13
	jmp 1b

#read system sectors to 0x10000(only read 2*64KB for reducing loading time)
sread: 	.word 5
head:	.word 0
track:	.word 0
2:
	mov $0x1000, %ax
	mov %ax, %es
	xor %bx, %bx
repeat:
	mov %es, %ax
	cmp $0x3000, %ax
	jb  ok1
	jmp 3f
ok1:
	mov $18, %ax
	sub sread, %ax
	mov %ax, %cx
	shl $9, %cx
	add %bx, %cx
	jnc ok2
	xor %ax, %ax
	sub %bx, %ax
	shr $9, %ax
ok2:
	call read_track
	mov %ax, %cx
	add sread, %ax
	cmp $18, %ax
	jl	ok3
	mov $1, %ax
	sub head, %ax
	jne ok4
	incw track
ok4:
	mov %ax, head
	xor %ax, %ax
ok3:
	mov %ax, sread
	shl $9, %cx
	add %cx, %bx
	jnc repeat
	mov %es, %ax
	add $0x1000, %ax
	mov %ax, %es
	xor %bx, %bx
	jmp repeat
	

#then jump to 0x90200
3:
	ljmp $0x9000, $0x0200

read_track:
	push %ax
	push %bx
	push %cx
	push %dx
	mov track, %dx
	mov sread, %cx
	inc %cx
	mov %dl, %ch
	mov head, %dx
	mov %dl, %dh
	mov $0, %dl
	and $0x0100, %dx
	mov $2, %ah
	int $0x13
	jc  bad_rt
	pop %dx
	pop %cx
	pop %bx
	pop %ax
	ret

bad_rt:
	mov $0, %ax
	mov $0, %dx
	int $0x13
	pop %dx
	pop %cx
	pop %bx
	pop %ax
	jmp read_track

output:
	.ascii "Loading System..."
	
.org 510
	.word 0xaa55

